package com.yuwen.yuwenRPC.serializer;

import java.io.*;

/**
 * @ClassNameJDKSerializer
 * @Description TODO
 * @Author钰玟
 * @Date2025/3/29 下午9:08
 * @Version 1.0
 **/

public class JdkSerializer implements Serializer{
    /**
     * 序列化
     * @param obj 被序列化的对象
     * @return 字节数组
     * @throws IOException IOE异常
     */
    @Override
    public <T> byte[] serialize(T obj) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);

            oos.writeObject(obj);
            oos.close();
            return baos.toByteArray();

    }
    /**
     * 反序列化
     * @param bytes 字节数组
     * @param clazz T的 类型
     * @return T类
     * @param <T> 泛型
     * @throws IOException IOE异常
     */
    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(bais);
        try {
            return (T) ois.readObject();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }finally {
            ois.close();
        }
    }
}
